using Android.App;
using Android.OS;
using Android.Widget;

using System;
using CapstoneProject.Models;
using System.Collections.Generic;
using System.Linq;

namespace CapstoneProject.Activities
{
    [Activity(Label = "Create New User")]
    public class NewUserActivity : Activity
    {
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Newuser);

            Button createUserButton = FindViewById<Button>(Resource.Id.CreateButton);
            createUserButton.Click += Create;

            Button cancelButton = FindViewById<Button>(Resource.Id.CancelButton);
            cancelButton.Click += delegate { StartActivity(typeof(HomeActivity)); };
        }

        private void Create(object sender, EventArgs e)
        {
            TextView newUserError = FindViewById<TextView>(Resource.Id.NewUserErrors);
            EditText usernameField = FindViewById<EditText>(Resource.Id.UsernameField);
            EditText passwordField = FindViewById<EditText>(Resource.Id.PasswordField);
            EditText retypePwField = FindViewById<EditText>(Resource.Id.RetypePasswordField);
            if (String.IsNullOrEmpty(passwordField.Text) || String.IsNullOrEmpty(usernameField.Text) || String.IsNullOrEmpty(retypePwField.Text))
            {
                newUserError.Text = "All fields are required.";
            }
            else if (passwordField.Text != retypePwField.Text)
            {
                newUserError.Text = "Passwords do not match.";
            }
            else
            {
                User existingUser = ((CapstoneApplication)Application).UserRepository.GetAllUsers().FirstOrDefault(u => u.Username == usernameField.Text);
                if (existingUser == null)
                {
                    ((CapstoneApplication)Application).UserRepository.AddUser(usernameField.Text, passwordField.Text);

                    Finish();
                }
                else
                {
                    newUserError.Text = "Username already exists.";
                }
            }
        }
    }
}